<template>
	<el-container>
		<el-aside width="300px" v-loading="showDicloading">
			<el-container>
				<el-header>
					<el-input placeholder="输入关键字进行过滤" v-model="dictFilterText" clearable></el-input>
				</el-header>
				<el-main class="nopadding">
					<el-tree ref="dict" class="menu" node-key="dictId" :data="dictList" :props="dictProps" :highlight-current="true" :expand-on-click-node="false" :filter-node-method="dictFilterNode" @node-click="dictClick">
						<template #default="{node, data}">
							<span class="custom-tree-node" :class="data.status=='1'?'disabled':''">
								<span class="label">{{ data.dictName }}</span>
								<span class="code">{{ data.dictType }}</span>
								<span class="do">
									<el-button-group>
										<el-button icon="el-icon-edit" size="small" @click.stop="dictEdit(data)"></el-button>
										<el-button icon="el-icon-delete" size="small" @click.stop="dictDel(node, data)"></el-button>
									</el-button-group>
								</span>
							</span>
						</template>
					</el-tree>
				</el-main>
				<el-footer style="height:51px;">
					<el-button-group style="width: 100%">
						<el-button type="primary" size="small" icon="el-icon-plus" @click="addDict" style="width:50%">字典类型</el-button>
						<el-button type="danger" size="small" icon="el-icon-refresh" @click.stop="refreshCache" style="width:50%">刷新缓存</el-button>
					</el-button-group>

				</el-footer>
			</el-container>
		</el-aside>
		<el-container class="is-vertical">
			<el-header>
				<div class="left-panel">
					<el-button type="primary" icon="el-icon-plus" @click="addInfo"></el-button>
					<el-button type="danger" plain icon="el-icon-delete" :disabled="selection.length==0" @click="batch_del"></el-button>
				</div>
			</el-header>
			<el-main class="nopadding" v-loading="loading">
				<jdTable ref="table" :apiObj="listApi" row-key="dictId" :params="listApiParams" @selection-change="selectionChange" stripe :paginationLayout="'prev, pager, next'">
					<el-table-column type="selection" width="50"></el-table-column>
					<el-table-column label="" width="100">
						<template #default>
							<el-tag class="move" style="cursor: move;"><el-icon-d-caret style="width: 1em; height: 1em;"/></el-tag>
						</template>
					</el-table-column>
					<el-table-column label="键名" prop="dictLabel">
						<template #default="scope">
							<span v-if="scope.row.listClass=='default'">{{scope.row.dictLabel}}</span>
							<el-tag :type="scope.row.listClass" v-if="scope.row.listClass!='default'">{{scope.row.dictLabel}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="键值" prop="dictValue" ></el-table-column>
					<el-table-column label="状态" prop="status" align="center">
						<template #default="scope">
							<el-switch v-model="scope.row.status" @change="changeSwitch($event, scope.row)" :loading="scope.row.$switch_yx" active-value="0" inactive-value="1"></el-switch>
						</template>
					</el-table-column>
					<el-table-column label="操作" fixed="right" align="center" width="150">
						<template #default="scope">
							<el-button-group>
								<el-button text type="primary" @click="table_edit(scope.row, scope.$index)" class="button">编辑</el-button>
								<el-popconfirm title="确定要删除吗？" @confirm="table_del(scope.row, scope.$index)">
									<template #reference>
										<el-button text type="primary" class="button">删除</el-button>
									</template>
								</el-popconfirm>
							</el-button-group>
						</template>
					</el-table-column>
				</jdTable>
			</el-main>
		</el-container>
	</el-container>

	<dict-dialog @close="refresh" v-if="dialog.dict" ref="dictDialog" @success="handleDictSuccess" @closed="dialog.dict=false"></dict-dialog>
	<list-dialog  v-if="dialog.list" ref="listDialog" @success="handleListSuccess" @closed="dialog.list=false"></list-dialog>

</template>

<script>
	import dictDialog from './dict'
	import listDialog from './list'
	import Sortable from 'sortablejs'

	export default {
		name: 'dict',
		components: {
			dictDialog,
			listDialog
		},
		data() {
			return {
				ids: [],
				dialog: {
					dict: false,
					info: false
				},
				showDicloading: true,
				dictList: [],
				dictFilterText: '',
				dictProps: {
					label: 'name'
				},
				dictType: undefined,
				listApi: null,
				listApiParams: {},
				selection: [],
				loading: false
			}
		},
		watch: {
			dictFilterText(val) {
				this.$refs.dict.filter(val);
			}
		},
		mounted() {
			this.getDict()
			this.rowDrop()
		},
		methods: {
			//加载树数据
			async getDict(){
				var res = await this.$API.system.dict.type.listType.get({pageSize: 1000});
				//var res = await this.$API.system.dict.tree.get();
				this.showDicloading = false;
				this.dictList = res.data.rows;
				//获取第一个节点,设置选中 & 加载明细列表
				var firstNode = this.dictList[0];
				if(firstNode){
					this.dictType = firstNode.dictType;
					this.$nextTick(() => {
						this.$refs.dict.setCurrentKey(firstNode.dictId)
					})
					this.listApiParams = {
						dictType: firstNode.dictType
					}
					this.listApi = this.$API.system.dict.data.listData;
				}
			},
			//树过滤
			dictFilterNode(value, data){
				if (!value) return true;
				var targetText = data.dictName + data.dictType;
				return targetText.indexOf(value) !== -1;
			},
			//树增加
			addDict(){
				this.dialog.dict = true
				this.$nextTick(() => {
					this.$refs.dictDialog.open()
				})
			},
			//编辑树
			dictEdit(data){
				this.dialog.dict = true
				this.$nextTick(() => {
					//console.log(this.$refs.dict)
					//var editNode = this.$refs.dict.getNode(data.id);
					// var editNodeParentId =  editNode.level==1?undefined:editNode.parent.data.id
					// data.parentId = editNodeParentId
					this.$refs.dictDialog.open('edit').setData(data)
				})
			},
			//树点击事件
			dictClick(data){
				this.dictType = data.dictType;
				this.$refs.table.reload({
					dictType: data.dictType
				})
			},
			//删除树
			dictDel(node, data){
				this.$confirm(`确定要删除"${data.dictType}"项吗？`, '提示', {
					type: 'warning'
				}).then(async () => {
					this.showDictloading = true;

					//删除字典
					let res = await this.$API.system.dict.type.delType.delete(data.dictId);
					if (res.code == 200){
						//删除节点是否为高亮当前 是的话 设置第一个节点高亮
						var dicCurrentKey = this.$refs.dict.getCurrentKey();
						this.$refs.dict.remove(data.dictId);

						if(dicCurrentKey == data.dictId){
							var firstNode = this.dictList[0];
							if(firstNode){
								this.dictType = firstNode.dictType;
								this.$refs.dict.setCurrentKey(firstNode.dictId);
								this.$refs.table.upData({
									dictType: firstNode.dictType
								})
							}else{
								this.listApi = null;
								this.$refs.table.tableData = []
							}
						}
						this.$message.success("操作成功")
					}else {
						this.$message.error(res.msg)
					}
					this.showDictloading = false;

				}).catch(() => {

				})
			},
			//行拖拽
			rowDrop(){
				const _this = this
				const tbody = this.$refs.table.$el.querySelector('.el-table__body-wrapper tbody')
				Sortable.create(tbody, {
					handle: ".move",
					animation: 300,
					ghostClass: "ghost",
					async onEnd({ newIndex, oldIndex }) {
						this.loading = true;
						const tableData = _this.$refs.table.tableData
						const currRow = tableData.splice(oldIndex, 1)[0]
						tableData.splice(newIndex, 0, currRow)

						var res = {}
						// 字典数据排序
						res = await _this.$API.system.dict.data.changeSort.put(tableData);
						if(res.code == 200){
							_this.$refs.table.tableData = [];
							_this.$refs.table.reload({dictType: _this.dictType});
							this.loading = false;
						}
					}
				})
			},
			//添加字典数据
			addInfo(){
				this.dialog.list = true
				this.$nextTick(() => {
					var currentId = this.$refs.dict.getCurrentKey();
					const data = {
						dictId: currentId,
						dictType: this.dictType
					}
					this.$refs.listDialog.open().setData(data)
				})
			},
			// 刷新
			refresh(){
				this.getDict()
			},
			//编辑字典数据
			table_edit(row){
				this.dialog.list = true
				this.$nextTick(() => {
					this.$refs.listDialog.open('edit').setData(row)
				})
			},
			//删除字典数据
			async table_del(row, index){
				var id = row.dictCode;
				var res = await this.$API.system.dict.data.delData.delete(id);
				if(res.code == 200){
					this.$refs.table.tableData.splice(index, 1);
					this.$message.success("删除成功")
				}else{
					this.$alert(res.msg, "提示", {type: 'error'})
				}
			},
			//批量删除字典数据
			async batch_del(){
				this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
					type: 'warning'
				}).then(async () => {
					const loading = this.$loading();
					var res = await this.$API.system.dict.data.delData.delete(this.ids);
					this.listApi = this.$API.system.dict.data.listData;
					if(res.code == 200){
						// 加载字典列表
						this.$refs.table.reload({
							dictType: this.dictType
						})
						this.$message.success("删除成功")
					}else{
						this.$alert(res.msg, "提示", {type: 'error'})
					}
					loading.close();
				}).catch(() => {

				})
			},
			//表格选择后回调事件
			selectionChange(selection){
				this.selection = selection;
				console.log(selection,'表格选择后回调事件')
				this.ids = selection.map(item => item.dictCode)
				console.log(this.ids,'表格选择后回调事件IDS')
				// this.single = selection.length!=1
				// this.multiple = !selection.length
			},
			//表格内开关事件
			async changeSwitch(val, row){
				//1.还原数据
				row.status = row.status == '1'?'0':'1'
				//2.执行加载
				row.$switch_yx = true;
				//3.等待接口返回后改变值
				setTimeout(async ()=>{
					delete row.$switch_yx;
					row.status = val;
					await this.$API.system.dict.data.changeStatus.put(row);
					this.$message.success("操作成功")
				}, 0)
			},
			//本地更新数据
			handleDictSuccess(data, mode){
				if(mode=='add'){
					data.id = new Date().getTime()
					if(this.dictList.length > 0){
						this.$refs.table.upData({
							code: data.code
						})
					}else{
						this.listApiParams = {
							code: data.code
						}
						this.listApi = this.$API.dict.info;
					}
					this.$refs.dict.append(data, data.parentId[0])
					this.$refs.dict.setCurrentKey(data.id)
				}else if(mode=='edit'){
					var editNode = this.$refs.dict.getNode(data.dictId);
					//判断是否移动？
					var editNodeParentId =  editNode.level==1?undefined:editNode.parent.data.id
					if(editNodeParentId != data.parentId){
						var obj = editNode.data;
						this.$refs.dict.remove(data.dictId)
						this.$refs.dict.append(obj, data.parentId[0])
					}
					Object.assign(editNode.data, data)
				}
			},
			//本地更新数据
			handleListSuccess(data, mode){
				if(mode=='add'){
					data.dictId = new Date().getTime()
					this.$refs.table.tableData.push(data)
					this.$refs.table.refresh();
				}else if(mode=='edit'){
					this.$refs.table.tableData.filter(item => item.dictCode===data.dictCode ).forEach(item => {
						Object.assign(item, data)
					})
				}
			},
			refreshCache(){
				this.$confirm('此操作将重置字典的缓存, 是否要继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					await this.$API.system.dict.type.refreshCache.delete();
					this.$message.success("操作成功");
				}).catch(() => {
				});
			}
		}
	}
</script>

<style scoped>
	.menu:deep(.el-tree-node__label) {display: flex;flex: 1;height:100%;}
	.custom-tree-node {display: flex;flex: 1;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 24px;height:100%;}
	.custom-tree-node .code {font-size: 12px;color: #999;}
	.custom-tree-node .do {display: none;}
	.custom-tree-node:hover .code {display: none;}
	.custom-tree-node:hover .do {display: inline-block;}
	.custom-tree-node.disabled{text-decoration:line-through; color: #aaa;}
	.custom-tree-node.disabled .code {font-size: 12px;color: #aaa;}
</style>
